<template>
  <el-dialog title="权限分配" :visible="showPermissionDialog" @close="handleBtnCancel">
    <!-- :key="roleId"为什么要加上这个呢, 因为el-tree被复用, 之前的选项还存在 -->
    <el-tree
      ref="treeRef"
      :key="roleId"
      v-loading="loading"
      :data="permData"
      :props="defaultProps"
      default-expand-all
      show-checkbox
      node-key="id"
      check-strictly
      :default-checked-keys="selectedKey"
    />
    <el-row type="flex" justify="center">
      <el-button size="small" @click="handleBtnCancel">取消</el-button>
      <el-button type="primary" size="small" @click="handleBtnOk">保存</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { tranListToTreeData } from '@/utils/index'
import { getRoleDetail, assignPermission } from '@/api/setting'

export default {
  props: {
    showPermissionDialog: {
      type: Boolean,
      default: false

    }
  },

  data() {
    return {
      permData: [], // 权限树形结构数据
      defaultProps: { label: 'name' },
      selectedKey: [], // 默认选中项 结合node-key
      loading: false, // 树形加载
      roleId: null // 分配当前角色id
    }
  },
  mounted() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      this.loading = true
      this.permData = tranListToTreeData(await getPermissionList(), '0')
      this.loading = false
    },
    async getRoleDetail(roleId) {
      this.selectedKey = [] // 初始化状态
      this.roleId = roleId
      const { permIds } = await getRoleDetail(roleId)
      this.selectedKey = permIds
    },
    // 点击保存分配权限
    async handleBtnOk() {
      await assignPermission({ permIds: this.$refs.treeRef.getCheckedKeys(), id: this.roleId })
      this.$message.success('权限分配成功')
      this.$emit('update:showPermissionDialog', false)
    },
    // 点击取消
    handleBtnCancel() {
      this.selectedKey = [] // 初始化状态

      // 关闭弹框
      this.$emit('update:showPermissionDialog', false)
    }
  }
}

</script>
<style lang='less' scoped>
</style>
